<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'termin-form',
	'enableAjaxValidation'=>false,
        'htmlOptions'=>array(
            'style'=>'position: relative;',
        ),
    )); 
?>

<div id="terminInfo">
    <div id="terminInfoHeader">Opcje dodatkowe</div>
    <div id="terminInfoContent">
        <table><tr><td style="vertical-align: top !important;"><u>Powtarzalność:</u><br/>
        <?php echo CHTML::radioButtonList('Terminy[powtarzalnosc]', 'D', array('W'=>'co tydzień', 'D'=>'jednorazowo')); ?><br/><br/>
        </td><td style="vertical-align: top !important;"><u>Stanowisko:</u><br/>
        <?php $stanowiska = array();
        foreach($cwiczenie->stanowiskaCwiczenia as $s)
            $stanowiska[$s->idStanowiska] = $s->stanowisko->nazwa;
        echo CHtml::dropDownList('Terminy[idStanowiska]', 1, $stanowiska, array(
            'style'=>'width: 150px;',
        )); ?>
        </td></tr></table>
    </div>
</div>
<div class="form wide">


<?php
    function phpTerminyToJsArray($input) {
        $js = "var terminy = new Array();";

        foreach($input as $i=>$day) {
            $js .= "var result_1 = new Array();";
            foreach($day as $j=>$time) {
                $js .= "var result_2 = new Array();";
                foreach($time as $l=>$val) {
                    $js .= "result_2[".$l."] = '".$val."';";
                }
                $js .= "result_1[".$j."] = result_2;";
            }
            $js .= "terminy[".$i."] = result_1;";
        }

        return $js;
    }

     function phpLekarzeToJsArray($input) {
        $js = "var lekarze = new Array();";

        foreach($input as $i=>$name) {
            $js .= "lekarze[".$i."] = '".$name."';";
        }

        return $js;
    }


    $today = time();
    $oneDay = 24 * 60 * 60;

    $week = array();
    $weekParsed = "[";
    $offset = 0; // 0 = today is Monday

    while(date('N', $today+$offset*$oneDay) != 1)
            $offset--;

    for($i = 0; $i < 7; $i++) {
        $week[$i] = $today+($offset+$i)*$oneDay;
        $weekParsed .= '\''.$week[$i].'\',';
    }
    $weekParsed = substr($weekParsed, 0, strlen($weekParsed)-1).']';

    $terminy = Terminy::model()->getDostepneTerminy($week[0], $cwiczenie->idCwiczenia);
    //$terminy = array();
    $c = Cwiczenie::model()->findAll();
    /*$l = array();
    foreach ($l as $lekarz) {
        $lekarze[$lekarz->idLekarz] = $lekarz->fullName;
    }*/
    

    Yii::app()->clientScript->registerScript('globals', "
        var weekOffset = 0;
        ".phpTerminyToJsArray($terminy).
        // phpLekarzeToJsArray($lekarze)."
        "
        var klik = function(event) {
                var g = event.target.parentNode.childNodes[0].id.split('_');
                var godzina = 4*parseInt(g[1]) + parseInt(g[2]);
                var dzien = event.target.cellIndex-1;
                var dzienFull = $('#tableContainer th').get(dzien+1).innerHTML;
                var dzienTyg = $('#tableContainer th:eq('+(dzien+1)+')').find('span')[0].innerHTML;
                var d = $('#tableContainer th:eq('+(dzien+1)+')').attr('id').split('_');
                var klik = $('input:radio[name=klik]:checked').val();
                if (klik == 's') {
                    $('#Terminy_data').val(d[1]);
                    $('#Terminy_dzien_tygodnia').val(dzien);
                    $('#Terminy_godzina_poczatek').val(g[1]+':'+(g[2]=='0' ? '00' : g[2]*15)+':00');
                } else {
                    $('#Terminy_godzina_koniec').val(g[1]+':'+(g[2]=='0' ? '00' : g[2]*15)+':00');
                }
                var powt = $('input:radio[name=Terminy[powtarzalnosc]]:checked').val();
                $('#info_'+klik).val(d[1]+', '+g[1]+':'+(g[2]=='0' ? '00' : g[2]*15));
                if ($('#info_s').val() && $('#info_k').val())
                    $('#Termin_Submit').removeAttr('disabled');
            }
            var nextW = function() {
                weekOffset++;
                $.ajax({
                    type: 'POST',
                    url: '".CController::createUrl('dynamicTerminy1')."',
                    data: {'week': ".$weekParsed.", 'today': '".$today."', 'weekOffset': weekOffset, 'idCwiczenia': ".$cwiczenie->idCwiczenia."},
                    success: function(data) {
                        $('#tableContainer').html(data);
                        $('#terminTbody').click(function(event) {klik(event);});
                        $('#nextWeek').click(function(event) {nextW(event);});
                        $('#prevWeek').click(function(event) {prevW(event);});
                    }
                });
                
            }

            var prevW = function() {
                weekOffset--;
                $.ajax({
                    type: 'POST',
                    url: '".CController::createUrl('dynamicTerminy1')."',
                    data: {'week': ".$weekParsed.", 'today': '".$today."', 'weekOffset': weekOffset, 'idCwiczenia': ".$cwiczenie->idCwiczenia."},
                    success: function(data) {
                        $('#tableContainer').html(data);
                        $('#terminTbody').click(function(event) {klik(event);});
                        $('#nextWeek').click(function(event) {nextW(event);});
                        $('#prevWeek').click(function(event) {prevW(event);});
                    }
                });
                
            }
    ", CClientScript::POS_HEAD);
    
    Yii::app()->clientScript->registerScript('rezerwuj', "
        var rezerwuj = function(d, g, lId, lName) {
            g_ = g.split(':');
            $('#Wizyta_rejestracjaInfo').val(lName + ' (' + d + ', ' + g_[0] + ':' + ( g_[1] == '0' ? '00' : g_[1] ) + ')');
            $('#Wizyta_idLekarz').val(lId);
            $('#Wizyta_Termin').val(d + ' ' + g);
            $('#Wizyta_Submit').removeAttr('disabled');
        }
    ", CClientScript::POS_BEGIN);

    Yii::app()->clientScript->registerScript('main', "
        window.addEventListener('load', function() {
            var d = new Date();
            var h = d.getHours();
            
            var m = parseInt(d.getMinutes()/15);
            $('#terminTbody').scrollTo( $('#hour_'+h+'_'+m), 800 );
            $('#nextWeek').click(function(event) {nextW(event);});
            $('#prevWeek').click(function(event) {prevW(event);});
            $('#terminTbody').click(function(event) {klik(event);});
        }, false);
    ");

?>

	<p class="note">Pola oznaczone <span class="required">*</span> są wymagane.</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo CHTML::label('Wybrane ćwiczenie', 'cwiczenie'); ?>
		<?php echo CHTML::textField('Ćwiczenie', $cwiczenie->nazwa, array('disabled'=>'yes', 'size'=>30)); ?>
                <?php echo $form->hiddenField($model,'idCwiczenia',array('value'=>$cwiczenie->idCwiczenia));?>
	</div>
        
        <div class="row">
                <?php
                    $klik = array(
                        's'=>'początek bloku',
                        'k'=>'koniec bloku',
                    )
                ?>
		<?php echo CHTML::label('Kliknięcie wybiera', 'klik'); ?>
		<?php echo CHTML::radioButtonList('klik', 's', $klik); ?>
                <?php //echo $form->hiddenField($model,'idCwiczenia',array('value'=>$cwiczenie->idCwiczenia));?>
	</div>

        <div class="row">
		<?php echo CHTML::label('Wybrany początek bloku','info_p'); ?>
		<?php echo CHtml::textField('info_s', '', array('disabled'=>'yes', 'size'=>20)); ?>
                <?php echo $form->hiddenField($model,'data');?>
                <?php echo $form->hiddenField($model,'dzien_tygodnia');?>
                <?php echo $form->hiddenField($model,'godzina_poczatek');?>
        </div>
        
        <div class="row">
		<?php echo CHTML::label('Wybrany koniec bloku','info_p'); ?>
		<?php echo CHtml::textField('info_k', '', array('disabled'=>'yes', 'size'=>20)); ?>
                <?php echo $form->hiddenField($model,'godzina_koniec');?>
        </div>
	
        <br />
	

        <?php
        echo "<div id='tableContainer'><table class='scrollTable'><thead class='fixedHeader'><tr><th id='prevWeek' class='hour'>";
        foreach($week as $day) {
            echo "<th".($day==$today?" class='today'":"")." id='day_".date('Y-m-d', $day)."'><span>".Terminy::model()->dayPL(date('N', $day))."</span><br />"
                 .date('j', $day)." ".Terminy::model()->monthPL(date('n', $day))." ".date('Y', $day)."</th>";
        }
        echo "<th id='nextWeek' class='filler'></th></tr></thead><tbody id='terminTbody' class='scrollContent'>";
        for($i = 0; $i < 96; $i++) {
            //echo "<tr><td class='hour'>".(($i-$i%4)/4).":".($i%4==0?"00":$i%4*15)."</td>";
            echo "<tr><td class='hour' id='hour_".(($i-$i%4)/4)."_".($i%4)."'>".(($i%4==0) ? ($i/4).":00" : "")."</td>";
            $j = 0;
            foreach($week as $day) {
                //if (isset($terminy[$j][$i])) {
                    $class = " reserved";
                    foreach ($terminy[$j][$i] as $l) {
                        if ($l == 'F') {
                            $class = "";
                        }
                    }
                    foreach ($terminy[$j][$i] as $l) {
                        if ($l == 'T' || $l == 'R') {
                            $class = " free";
                        }
                    }
               /* } else {
                    $class = "";
                }*/
                echo "<td class='norm".($day==$today?" today":"")
                     .$class."'></td>";
                $j++;
            }
            echo "</tr>";
        }
        echo "</tbody></table></div>";
?>

	<div class="row buttons">
		<?php echo CHtml::submitButton('Zatwierdź',  array('disabled'=>'yes', 'id'=>'Termin_Submit')); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->